<template>
  <view class="mxp-collapse" :style="[cusStyle]" :class="cusClass">
    <mxp-line :color="listBorderColor"></mxp-line>
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
  import MxpLine from '@/mxp-ui/mxp-line/mxp-line.vue';
  import { publicStyeProps } from '../mxp-tool/utils/public-props';
  import { type PropType, computed, onBeforeMount, onUnmounted, provide, ref, watch } from 'vue';
  import type { $AllColorStr } from '@/mxp-ui/mxp-tool/types/interface';
  import { getOnlyID } from '../mxp-tool/utils/common';
  import { type CollapseID, type MxpCollapseProps, collapseInjectKey, mxpCollapseStore } from '../mxp-tool/store/mxp-store-collapse';
  defineOptions({
    name: 'mxp-collapse',
  });
  const props = defineProps({
    /** 顶部边框颜色(如不需要边框可设为fasle) */
    listBorderColor: { type: [Boolean, String] as PropType<$AllColorStr | boolean>, default: false },
    /** 折叠动画的时间(单位：毫秒) */
    duration: { type: Number, default: 300 },
    /** 当前展开并激活的面板的name (即<mxp-collapse-item>中指定的 name) */
    modelValue: { type: [Array] as PropType<(number | string)[] | number | string>, default: () => [] },
    /** 是否只允许同时只展开一个 */
    accordion: { type: Boolean, default: true },
    /** 项目展开和关闭图标的位置，可选left,right */
    iconPosition: { type: String as PropType<'left' | 'right'>, default: 'right' },
    /** 标题上下边框颜色 (如不需要边框可设为none)  */
    itemBorderColor: { type: [Boolean, String] as PropType<$AllColorStr | boolean | 'transparent'>, default: undefined },
    /** 是否显示最后一项的边框  */
    showLastborder: { type: Boolean, default: false },
    ...publicStyeProps,
  });
  defineSlots<{
    /** 主体内容 */
    default?: () => void;
  }>();
  const emits = defineEmits<{
    (e: 'change', str: (number | string)[], key: number | string): void;
    (e: 'update:modelValue', str: (number | string)[]): void;
  }>();
  const id: CollapseID = `__MXP-COLLAPSE-${getOnlyID('mxp-collapse')}__`;
  const collapseStore = mxpCollapseStore();
  /** 展开的name数组 */
  const unfoldNameList = ref<(number | string)[]>(getDefaultUnfoldNameList());

  watch(
    () => props.modelValue,
    () => {
      unfoldNameList.value = getDefaultUnfoldNameList();
    }
  );

  /** 得到默认选中的 key */
  function getDefaultUnfoldNameList() {
    const _unfoldNameList = Array.isArray(props.modelValue) ? props.modelValue : props.modelValue || props.modelValue === 0 ? [props.modelValue] : [];
    if (props.accordion && _unfoldNameList.length > 0) {
      return [_unfoldNameList[_unfoldNameList.length - 1]!];
    }
    return _unfoldNameList;
  }

  /**
   * 更新折叠状态(如果是折叠状态就删除 key ，如果是未折叠状态就添加 key)
   */
  function changeUnfoldByKey(key: number | string) {
    const findkey = unfoldNameList.value.findIndex((el) => el === key);
    if (props.accordion) {
      unfoldNameList.value = findkey > -1 ? [] : [key];
    } else {
      if (findkey > -1) {
        unfoldNameList.value.splice(findkey, 1);
      } else {
        unfoldNameList.value.push(key);
      }
    }

    emits('update:modelValue', unfoldNameList.value);
    emits('change', unfoldNameList.value, key);
  }

  const collapseProps = computed<MxpCollapseProps>(() => {
    const _collapseProps: MxpCollapseProps = {
      unfoldNameList: unfoldNameList.value,
      iconPosition: props.iconPosition,
      duration: props.duration,
      itemBorderColor: props.itemBorderColor,
      showLastborder: props.showLastborder,
    };
    return _collapseProps;
  });
  watch(
    () => collapseProps.value,
    (val) => {
      collapseStore.actions.setFormProps(id, val);
    }
  );
  collapseStore.actions.setFormProps(id, collapseProps.value);
  collapseStore.actions.setChangeUnfoldByKeyFun(id, changeUnfoldByKey);
  provide<CollapseID>(collapseInjectKey, id);
  onBeforeMount(() => {
    provide(collapseInjectKey, id);
  });

  onUnmounted(() => {
    // 删除
    collapseStore.actions.delItemByID(id);
  });
</script>

<style scoped lang="scss">
  .mxp-collapse {
    display: flex;
    flex-direction: column;
  }
</style>
